import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Avatar, 
  Typography, 
  Row, 
  Col, 
  Form, 
  Input, 
  Button, 
  Alert, 
  Space,
  message,
  Skeleton,
  Tag,
} from 'antd';
import {
  UserOutlined,
  MailOutlined,
  EditOutlined,
  SaveOutlined,
  CloseOutlined,
  CalendarOutlined,
} from '@ant-design/icons';
import { useAuthStore } from '../../store/auth';

const { Title, Text, Paragraph } = Typography;

interface UpdateProfileData {
  email?: string;
  full_name?: string;
}

const ProfileSettings: React.FC = () => {
  const { user, updateUserProfile, isLoading } = useAuthStore();
  const [isEditing, setIsEditing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    if (user) {
      form.setFieldsValue({
        email: user.email,
        full_name: user.full_name,
      });
    }
  }, [user, form]);

  const handleSubmit = async (values: UpdateProfileData) => {
    try {
      setError(null);
      await updateUserProfile(values);
      message.success('个人信息更新成功！');
      setIsEditing(false);
    } catch (error: any) {
      const errorMessage = error.message || '更新失败，请重试';
      setError(errorMessage);
      message.error(errorMessage);
    }
  };

  const handleCancel = () => {
    setIsEditing(false);
    setError(null);
    form.setFieldsValue({
      email: user?.email,
      full_name: user?.full_name,
    });
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN');
  };

  if (!user) {
    return <Skeleton active avatar paragraph={{ rows: 6 }} />;
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题 */}
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'flex-start',
        marginBottom: '24px'
      }}>
        <div>
          <Title level={2} style={{ margin: 0, marginBottom: '8px' }}>
            <UserOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
            个人资料
          </Title>
          <Text type="secondary">管理您的个人信息和账户设置</Text>
        </div>
        {!isEditing && (
          <Button 
            type="primary"
            icon={<EditOutlined />}
            onClick={() => setIsEditing(true)}
          >
            编辑资料
          </Button>
        )}
      </div>

      <Row gutter={[24, 24]}>
        {/* 左侧：头像和基本信息 */}
        <Col xs={24} lg={8}>
          <Card style={{ textAlign: 'center', height: 'fit-content' }}>
            <div style={{ marginBottom: '16px' }}>
              <Avatar 
                size={80} 
                style={{ 
                  backgroundColor: '#1890ff',
                  fontSize: '32px',
                  fontWeight: 'bold'
                }}
                icon={<UserOutlined />}
              >
                {user.username?.charAt(0).toUpperCase()}
              </Avatar>
            </div>
            
            <Title level={4} style={{ marginBottom: '8px' }}>
              {user.full_name || user.username}
            </Title>
            
            <Text type="secondary" style={{ display: 'block', marginBottom: '4px' }}>
              @{user.username}
            </Text>
            
            <Text type="secondary" style={{ display: 'block', marginBottom: '4px', fontSize: '12px' }}>
              账号ID: {user.user_id}
            </Text>
            
            <Text type="secondary" style={{ display: 'block', marginBottom: '16px' }}>
              <MailOutlined style={{ marginRight: '4px' }} />
              {user.email}
            </Text>

            {user.is_superuser && (
              <Tag color="success" style={{ marginBottom: '16px' }}>
                系统管理员
              </Tag>
            )}

            <div style={{ marginTop: '16px', textAlign: 'left' }}>
              <Space direction="vertical" style={{ width: '100%' }}>
                <div>
                  <Text type="secondary" style={{ fontSize: '12px' }}>加入时间</Text>
                  <br />
                  <Text style={{ fontSize: '14px' }}>
                    <CalendarOutlined style={{ marginRight: '4px' }} />
                    {user.created_at ? formatDate(user.created_at) : '未知'}
                  </Text>
                </div>
                <div>
                  <Text type="secondary" style={{ fontSize: '12px' }}>最后登录</Text>
                  <br />
                  <Text style={{ fontSize: '14px' }}>
                    <CalendarOutlined style={{ marginRight: '4px' }} />
                    {user.last_login ? formatDate(user.last_login) : '从未登录'}
                  </Text>
                </div>
              </Space>
            </div>
          </Card>
        </Col>

        {/* 右侧：详细信息和编辑表单 */}
        <Col xs={24} lg={16}>
          <Card title="账户信息">
            {error && (
              <Alert
                message={error}
                type="error"
                showIcon
                closable
                onClose={() => setError(null)}
                style={{ marginBottom: '16px' }}
              />
            )}

            {isEditing ? (
              <Form
                form={form}
                layout="vertical"
                onFinish={handleSubmit}
                disabled={isLoading}
              >
                <Form.Item
                  label="用户名"
                  style={{ marginBottom: '24px' }}
                >
                  <Input value={user.username} disabled />
                </Form.Item>

                <Form.Item
                  label="账号ID"
                  style={{ marginBottom: '24px' }}
                >
                  <Input value={user.user_id} disabled />
                </Form.Item>

                <Form.Item
                  label="邮箱地址"
                  name="email"
                  rules={[
                    { required: true, message: '请输入邮箱地址' },
                    { type: 'email', message: '请输入有效的邮箱地址' }
                  ]}
                  style={{ marginBottom: '24px' }}
                >
                  <Input placeholder="请输入邮箱地址" />
                </Form.Item>

                <Form.Item
                  label="全名"
                  name="full_name"
                  style={{ marginBottom: '32px' }}
                >
                  <Input placeholder="请输入全名（可选）" />
                </Form.Item>

                <Form.Item style={{ marginBottom: 0 }}>
                  <Space>
                    <Button 
                      type="primary" 
                      htmlType="submit"
                      loading={isLoading}
                      icon={<SaveOutlined />}
                    >
                      保存更改
                    </Button>
                    <Button 
                      onClick={handleCancel}
                      icon={<CloseOutlined />}
                    >
                      取消
                    </Button>
                  </Space>
                </Form.Item>
              </Form>
            ) : (
              <div>
                <div style={{ marginBottom: '16px' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>用户名</Text>
                  <br />
                  <Text style={{ fontSize: '16px' }}>{user.username}</Text>
                </div>

                <div style={{ marginBottom: '16px' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>账号ID</Text>
                  <br />
                  <Text style={{ fontSize: '16px' }}>{user.user_id}</Text>
                </div>

                <div style={{ marginBottom: '16px' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>邮箱地址</Text>
                  <br />
                  <Text style={{ fontSize: '16px' }}>{user.email}</Text>
                </div>

                <div style={{ marginBottom: '16px' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>全名</Text>
                  <br />
                  <Text style={{ fontSize: '16px' }}>{user.full_name || '未设置'}</Text>
                </div>

                <div style={{ marginBottom: '16px' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>账户类型</Text>
                  <br />
                  <Tag color={user.is_superuser ? 'success' : 'default'} style={{ marginTop: '4px' }}>
                    {user.is_superuser ? '系统管理员' : '普通用户'}
                  </Tag>
                </div>

                <div style={{ marginBottom: '16px' }}>
                  <Text type="secondary" style={{ fontSize: '12px' }}>状态</Text>
                  <br />
                  <Tag color="success" style={{ marginTop: '4px' }}>
                    正常
                  </Tag>
                </div>
              </div>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default ProfileSettings; 